﻿using System;
using System.Linq;
using System.Windows.Forms;
using DesignerHelper.EventHandlers;
using SpreadsheetGear;
using SpreadsheetGear.Windows.Forms;
using WorkbookDesigner.Addons.SpreadsheetEditor.UI;
using WorkbookDesigner.Addons.WorkbookExplorer;
using System.Collections.Generic;
using DesignerHelper.Main;
using WorkbookDesigner.UI;
using DesignerHelper.Commands;

namespace WorkbookDesigner.Main
{
    public partial class MainWindow : Form, IMainWindow
    {
        public MainWindow(IWorkbookSet bookSet) : this()
        {
            HookEvents();
            _presenter.Init(bookSet);
        }

        public MainWindow(string[] args) : this()
        {
            HookEvents();
            _presenter.Init(args);
        }

        private MainWindow()
        {
            InitializeComponent();
            _presenter = new MainWindowPresenter(this);
        }

        public IFileOperator FileOperator => _presenter.Operator;

        private readonly MainWindowPresenter _presenter;

        private void MainWindow_Load(object sender, EventArgs e)
        {
            Text = DesignerHelper.Properties.Resources.MyName;
        }

        #region Workbook Form and view
        public IBookForm ActiveBookForm => ActiveMdiChild as WorkBookForm;

        public WorkbookView ActiveView => ActiveBookForm?.WorkbookView;

        IFileOperator IMainWindow.FileOperator => FileOperator;

        Form IMainWindow.GetForm()
        {
            return this;
        }
        #endregion

        #region 事件定义、处理

        private void _disableButton()
        {
            //toolStrip1.Enabled = false;
            buttonNew.Enabled =
            buttonOpen.Enabled =
            buttonSave.Enabled =
            buttonCopy.Enabled =
            buttonCut.Enabled =
            buttonPaste.Enabled =
            buttonPrint.Enabled =
            buttonReDo.Enabled =
            buttonUnDo.Enabled =
            buttonReplace.Enabled =
            buttonFind.Enabled =
            buttonHelp.Enabled =
            buttonPrintPreview.Enabled = false;

        }

        private void _disableMenu()
        {
            //menu_File.Enabled = false;
            menu_File_save.Enabled =
            menu_File_saveAs.Enabled =
            menu_File_saveAll.Enabled =
            menu_File_PageSetup.Enabled =
            menu_File_close.Enabled =
            menu_Edit.Enabled =
            menu_Insert.Enabled =
            menu_Format.Enabled =
            menu_Windows.Enabled =
            menu_Addons.Enabled =
            menu_Data.Enabled =
            menu_Help.Enabled = false;

        }

        private void _enableButton()
        {
            buttonNew.Enabled =
            buttonOpen.Enabled =
            buttonSave.Enabled =
            buttonCopy.Enabled =
            buttonCut.Enabled =
            buttonPaste.Enabled =
            buttonPrint.Enabled =
            buttonReDo.Enabled =
            buttonUnDo.Enabled =
            buttonReplace.Enabled =
            buttonFind.Enabled =
            buttonHelp.Enabled =
            buttonPrintPreview.Enabled = true;
        }

        private void _enableMenu()
        {
            menu_File_save.Enabled =
            menu_File_saveAs.Enabled =
            menu_File_saveAll.Enabled =
            menu_File_PageSetup.Enabled =
            menu_File_close.Enabled =
            menu_Edit.Enabled =
            menu_Insert.Enabled =
            menu_Format.Enabled =
            menu_Windows.Enabled =
            menu_Addons.Enabled =
            menu_Data.Enabled =
            menu_Help.Enabled = true;
        }

        private void DisableControlsForCellEvents(object sender, EventArgs e)
        {
            if (!(e is CellBeginEditEventArgs))
                return;
            _disableButton();
            _disableMenu();
            buttonCopy.Enabled = true;
            buttonPaste.Enabled = true;
            buttonCut.Enabled = true;
            buttonReDo.Enabled = true;
            buttonUnDo.Enabled = true;
        }

        private void DisableControlsForFormEvents(object sender, EventArgs e)
        {
            if (!(e is NoFormLeftEventArgs))
                return;
            _disableButton();
            _disableMenu();
            buttonNew.Enabled = true;
            buttonOpen.Enabled = true;
        }

        private void EnableControls(object sender, EventArgs e)
        {
            if (!(e is CellEndEditEventArgs))
                return;
            _enableButton();
            _enableMenu();
            buttonNew.Enabled = true;
            buttonOpen.Enabled = true;
        }

        private void EnableControls(object sender, CellCancelEditEventArgs e)
        {
            _enableButton();
            _enableMenu();
            buttonNew.Enabled = true;
            buttonOpen.Enabled = true;
        }
        private void EnableControls(object sender, FormExistEventArgs e)
        {
            _enableButton();
            _enableMenu();
        }
        private void HookEvents()
        {
            FileOperator.DisableUI += DisableControlsForFormEvents;
            FileOperator.EnableUI += EnableControls;
            FileOperator.CellBeginEditInternal += DisableControlsForCellEvents;
            FileOperator.CellCancelEditInternal += EnableControls;
            FileOperator.CellEndEditInternal += EnableControls;
        }
        private void UnhookEvents()
        {
            FileOperator.DisableUI -= DisableControlsForFormEvents;
            FileOperator.EnableUI -= EnableControls;
            FileOperator.CellBeginEditInternal -= DisableControlsForCellEvents;
            FileOperator.CellCancelEditInternal -= EnableControls;
            FileOperator.CellEndEditInternal -= EnableControls;
        }
        #endregion

        #region 控件方法
        private void addons_MyWorkbookExplorer_Click(object sender, EventArgs e)
        {
            _presenter.menu_Addons_MyWbExplorer_Click();
        }

        private void addons_RangeExplorer_Click(object sender, EventArgs e)
        {
            if(ActiveBookForm != null)
                Addons.Basic.ShowRangeExplorer(ActiveBookForm.WorkbookView);
        }

        private void addons_ShapeExplorer_Click(object sender, EventArgs e)
        {
            if (ActiveBookForm != null)
                Addons.Basic.ShowShapeExplorer(ActiveBookForm.WorkbookView);
        }

        private void addons_SpreadsheetEditor_Click(object sender, EventArgs e)
        {
            _presenter.menu_Addons_SpreadsheetEditor_Click();
        }

        private void addons_WorkbookExplorer_Click(object sender, EventArgs e)
        {
            if (ActiveBookForm != null)
                Addons.Basic.ShowWorkbookExplorer(ActiveBookForm.WorkbookView);
        }
        private void buttonFind_Click(object sender, EventArgs e)
        {
            FindReplaceDialog.ShowForm(this, FindReplaceDialog.OperationType.Find);
        }

        private void buttonNew_Click(object sender, EventArgs e)
        {
            FileOperator.NewFile();
        }

        private void buttonOpen_Click(object sender, EventArgs e)
        {
            FileOperator.OpenFiles();
        }

        private void buttonPrint_Click(object sender, EventArgs e)
        {
            ActiveBookForm?.Editor.Print(SpreadsheetGear.Printing.PrintWhat.Workbook);
        }

        private void buttonPrintPreview_Click(object sender, EventArgs e)
        {
            ActiveBookForm?.Editor.Preview(SpreadsheetGear.Printing.PrintWhat.Workbook);
        }

        private void buttonReDo_Click(object sender, EventArgs e)
        {
            ActiveBookForm?.Editor.ReDo();
        }

        private void buttonReplace_Click(object sender, EventArgs e)
        {
            FindReplaceDialog.ShowForm(this, FindReplaceDialog.OperationType.Replace);
        }

        private void buttonSave_Click(object sender, EventArgs e)
        {
            ActiveBookForm?.FileSaveAs();
        }

        private void buttonUnDo_Click(object sender, EventArgs e)
        {
            ActiveBookForm?.Editor.UnDo();
        }

        private void cascadeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            LayoutMdi(MdiLayout.Cascade);
        }

        private void edit_Clear_All_Click(object sender, EventArgs e)
        {
            ActiveBookForm?.Editor.ClearRangeSelection(Edit.ClearType.All);
        }

        private void edit_Clear_Contents_Click(object sender, EventArgs e)
        {
            ActiveBookForm?.Editor.ClearRangeSelection(Edit.ClearType.Contents);
        }

        private void edit_Clear_Format_Click(object sender, EventArgs e)
        {
            ActiveBookForm?.Editor.ClearRangeSelection(Edit.ClearType.Formats);
        }

        private void edit_ClearActiveSheet_Click(object sender, EventArgs e)
        {
            ActiveBookForm?.Editor.ClearWorksheet();
        }

        private void edit_Copy_Click(object sender, EventArgs e)
        {
            ActiveBookForm?.Editor.EditCopy();
        }

        private void edit_CopySheet_Click(object sender, EventArgs e)
        {
            ActiveBookForm?.Editor.CopySheet();
        }

        private void edit_Cut_Click(object sender, EventArgs e)
        {
            ActiveBookForm?.Editor.EditCut();
        }

        private void edit_DeleteCell_Click(object sender, EventArgs e)
        {
            DeleteCellsDialog.ShowStaticDialog(this);
        }

        private void edit_DeleteSheet_Click(object sender, EventArgs e)
        {
            ActiveBookForm?.Editor.DeleteActiveWorkSheet();
        }

        private void edit_Fill_Down_Click(object sender, EventArgs e)
        {
            ActiveBookForm?.Editor.FillRange(Edit.FillType.Down);
        }

        private void edit_Fill_Right_Click(object sender, EventArgs e)
        {
            ActiveBookForm?.Editor.FillRange(Edit.FillType.Right);
        }

        private void edit_FindAndReplace_Click(object sender, EventArgs e)
        {
            FindReplaceDialog.ShowForm(this, FindReplaceDialog.OperationType.Find);
        }

        private void edit_Goto_Click(object sender, EventArgs e)
        {
            ActiveBookForm?.ShowLocateRangeDialog();
        }

        private void edit_Paste_Click(object sender, EventArgs e)
        {
            //Edit.Commands command = new Edit.Commands(ActiveView);
            //command.PasteRange();
            ActiveBookForm?.Editor.EditPaste();
        }

        private void edit_PasteSpecial_Click(object sender, EventArgs e)
        {
            PasteSpecialDialog.ShowForm(this);
        }

        private void edit_ReDo_Click(object sender, EventArgs e)
        {
            ActiveBookForm?.Editor.ReDo();
        }

        private void edit_UnDO_Click(object sender, EventArgs e)
        {
            ActiveBookForm?.Editor.UnDo();
        }

        private void file_close_Click(object sender, EventArgs e)
        {
            ActiveBookForm?.GetForm().Close();
        }

        private void file_Exit_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void file_new_Click(object sender, EventArgs e)
        {
            FileOperator.NewFile();
        }

        private void file_PageSetup_Click(object sender, EventArgs e)
        {
            WbExplorer.GetInstance(this, WbExplorer.StartWith.PageSetup);
        }

        private void file_Preview_Range_Click(object sender, EventArgs e)
        {
            ActiveBookForm?.Editor.Preview(SpreadsheetGear.Printing.PrintWhat.Selection);
        }

        private void file_Preview_Sheet_Click(object sender, EventArgs e)
        {
            ActiveBookForm?.Editor.Preview(SpreadsheetGear.Printing.PrintWhat.Sheet);
        }

        private void file_Preview_Workbook_Click(object sender, EventArgs e)
        {
            ActiveBookForm?.Editor.Preview(SpreadsheetGear.Printing.PrintWhat.Workbook);
        }

        private void file_Print_Range_Click(object sender, EventArgs e)
        {
            ActiveBookForm?.Editor.Print(SpreadsheetGear.Printing.PrintWhat.Selection);
        }

        private void file_Print_Sheet_Click(object sender, EventArgs e)
        {
            ActiveBookForm?.Editor.Print(SpreadsheetGear.Printing.PrintWhat.Sheet);
        }

        private void file_Print_Workbook_Click(object sender, EventArgs e)
        {
            ActiveBookForm?.Editor.Print(SpreadsheetGear.Printing.PrintWhat.Workbook);
        }

        private void file_save_Click(object sender, EventArgs e)
        {
            ActiveBookForm?.SaveFile();
        }

        private void file_SaveAs_Click(object sender, EventArgs e)
        {
            ActiveBookForm?.FileSaveAs();
        }

        private void help_About_Click(object sender, EventArgs e)
        {
            using (FontDialog fd = new FontDialog())
            {
                fd.ShowDialog();
            }

        }

        private void help_test3_Click(object sender, EventArgs e)
        {
            Addons.TemplateConvertor.GetInstance(this);
        }

        private void hideOrShowFormulaBar_Click(object sender, EventArgs e)
        {
            formulaBar1.Visible = !formulaBar1.Visible;
            hideOrShowFormulaBar.Checked = formulaBar1.Visible;
        }

        private void hideOrShowStatusBar_Click(object sender, EventArgs e)
        {
            statusStrip1.Visible = !statusStrip1.Visible;
            hideOrShowStatusBar.Checked = statusStrip1.Visible;
        }
        private void insert_Cells_Click(object sender, EventArgs e)
        {
            InsertCellsDialog.ShowStaticDialog(this);
        }

        private void insert_DefineNames_Define_Click(object sender, EventArgs e)
        {
            ActiveBookForm?.ShowDefineNameDialog();
        }

        private void insert_DefineNames_DefineFromRange_Click(object sender, EventArgs e)
        {
            ActiveBookForm?.Editor.DefineNamesFromSelection();
        }

        private void insert_PageBreak_Click(object sender, EventArgs e)
        {
            ActiveBookForm?.Editor.InsertOrDeletePageBreaks();
        }

        private void insert_WorkSheets_Click(object sender, EventArgs e)
        {
            ActiveBookForm?.Editor.InsertWorkSheets();
        }

        private void MainWindow_FormClosed(object sender, FormClosedEventArgs e)
        {
            UnhookEvents();
        }

        private void MainWindow_MdiChildActivate(object sender, EventArgs e)
        {

        }

        private void menu_File_saveAll_Click(object sender, EventArgs e)
        {
            foreach (WorkBookForm wbf in FileOperator.AllFormsList.Where(x => x.ActiveBook.IsModified))
            {
                wbf.SaveFile();
            }
        }

        private void menu_Insert_DropDownOpening(object sender, EventArgs e)
        {
            if (ActiveBookForm == null)
            {
                insert_PageBreak.Enabled = false;
                return;
            }
            insert_PageBreak.Text = ActiveBookForm.HasPageBreaks ? "移除当前工作表中的分隔符" : "插入页面分隔符";
            IRange r = ActiveBookForm.WorkbookView.RangeSelection;
            if (r.Row == 0 || r.Column == 0)
                insert_PageBreak.Enabled = false;
            else
                insert_PageBreak.Enabled = true;
        }

        private void menu_Windows_DropDownOpening(object sender, EventArgs e)
        {
            var view = ActiveView;
            view.GetLock();
            tsmFreezePlane.Checked = view.ActiveWorksheet.WindowInfo.FreezePanes;
            view.ReleaseLock();
        }

        private void tileHorToolStripMenuItem_Click(object sender, EventArgs e)
        {
            LayoutMdi(MdiLayout.TileHorizontal);
        }

        private void tileVerToolStripMenuItem_Click(object sender, EventArgs e)
        {
            LayoutMdi(MdiLayout.TileVertical);
        }
        private void tsmFreezePlane_Click(object sender, EventArgs e)
        {
            var view = ActiveView;
            if (view == null)
                return;
            view.GetLock();
            view.ActiveWorksheet.WindowInfo.FreezePanes = !view.ActiveWorksheet.WindowInfo.FreezePanes;
            //view.ActiveWorksheet.Range.Columns.Hidden = false;
            tsmFreezePlane.Checked = view.ActiveWorksheet.WindowInfo.FreezePanes;
            view.ReleaseLock();
        }
        #endregion
    }
}
